﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UltrasonicTDPlatform
{
    /**
     * 硬件连接窗体类
     */
    public partial class ConnectionForm : Form
    {
        public Boolean connection_flag = false;
        public Boolean communication_flag = false;

        public ConnectionForm()
        {
            InitializeComponent();
            this.TopLevel = false;  //取消顶层显示
            
        }

        private void ConnectionForm_Load(object sender, EventArgs e)
        {
            //读取计算机所有串口
            string[] strCom = SerialPort.GetPortNames();
            if (strCom == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
                return;
            }
            //GetPortNames()方法:获取当前计算机的串行端口名的数组
            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
            {
                int idx = com_port.Items.Add(com);
                if (com.Equals("COM8"))
                    com_port.SelectedIndex = idx;
            }
        }

        /**
         * 打开并初始化USB串口
         */
        private void com_open_Click(object sender, EventArgs e)
        {
            if (com_port.Text.Equals(""))
            {
                MessageBox.Show("请选择com口！", "Error");
                return;
            }

            //判断端口是否打开
            // 未打开
            if (!serialPort1.IsOpen)
            {
                //判断是否已经打开串口控件禁用
                //如果串口是打开的，先关闭
                serialPort1.PortName = com_port.Text;
                serialPort1.BaudRate = 115200;
                serialPort1.DataBits = 8;
                serialPort1.StopBits = StopBits.One; //使用一个停止位
                serialPort1.Parity = Parity.None;
                serialPort1.RtsEnable = true;
                serialPort1.DtrEnable = true;//获取或设置一个值，改值在串行通讯过程中启用数据终端就绪（DTR）信号。
                serialPort1.ReadTimeout = 500;
                //打开串口
                serialPort1.Open();
                this.com_open.Text = "关闭串口";
                MainMenu.serialPort1 = serialPort1;

                //
                com_port.Enabled = false;

            }
            else
            {
                serialPort1.Close();
                this.com_open.Text = "打开串口";
                MainMenu.serialPort1 = null;

                com_port.Enabled = true;
            }
        }
    }
}
